package cn.ljq;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;

@ControllerAdvice  //统一异常处理
//Advice（通知）
//不管哪一层的异常，统一由这个控制器处理
public class ErrController {

    @ExceptionHandler(java.sql.SQLIntegrityConstraintViolationException.class)  //自定义可能出现的异常
    public String doSQLIntegrityConstraintViolationException(Exception ex ,Model model){

        System.out.println("SQL 主键编号重复 ：" + ex.getMessage());

        model.addAttribute("msg","SQL 主键编号重复：" + ex.getMessage());

        return "err";
    }


    @ExceptionHandler(SQLException.class)  //自定义可能出现的异常
    public String doSQLException(Exception ex , Model model){

        System.out.println("捕捉所有未定义的异常");

        System.out.println("SQL 操作异常 ：" + ex.getMessage());

        model.addAttribute("msg","SQL操作异常：" + ex.getMessage());

        return "err";
    }


    @ExceptionHandler(Exception.class)  //在最后来个全能捕捉异常  捕捉没有定义的所有异常
    public String doException(Exception ex,Model model){

        System.err.println("操作异常：" + ex.getMessage());

        System.out.println(ex.getCause());

        model.addAttribute("msg","操作异常：" + ex.getMessage());

        return "err";
    }


}
